<template>
  <van-uploader
    v-model="imgList"
    :after-read="afterRead"
    :before-delete="beforeDelete"
    :before-read="beforeRead"
    reupload
    :accept="accept"
    :max-count="limit"
    :max-size="maxSize"
  />
  <div class="tips">请上传大小不超过 <span>{{max}}MB</span>格式为<span>{{accept}}</span>的文件</div>
</template>

<script setup lang="ts" name="ImageUpload">
import { computed, ref, watch } from "vue";
import { http } from "@/utils/http";
import { closeToast, showFailToast, showLoadingToast, showSuccessToast } from "vant";

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  limit: {
    type: Number,
    default: 5
  },
  max: {
    type: Number,
    default: 5
  },
  accept: {
    type: String,
    default: ".jpg,.png,.jpeg"
  }
});
const emits = defineEmits(["update:modelValue"]);
const imgList = ref<Record<string, any>[]>([]);
const maxSize = computed(() => props.max * 1024 * 1024);

function afterRead(file: any) {
  const data = new FormData();
  data.append("file", file.file);
  showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    overlay: true,
    message: "上传中..."
  });
  // 此时可以自行将文件上传至服务器
  http
    .request({ url: "/resource/oss/upload", method: "post", data })
    .then((res: any) => {
      imgList.value.push({ url: res.data.url });
      const url = imgList.value
        .filter(item => item.url)
        .map(item => item.url)
        .join(",");
      emits("update:modelValue", url);
      showSuccessToast("上传成功");
    }).finally(() => closeToast());
}

function beforeDelete(file: { url: string }) {
  imgList.value = imgList.value.filter(item => item.url !== file.url);
  const url = imgList.value
    .filter(item => item.url)
    .map(item => item.url)
    .join(",");
  emits("update:modelValue", url);
}

function beforeRead(file: any) {
  console.log(file);
  const arr = file.name.split('.')
  const type = arr[arr.length - 1]
  const acceptTypes = props.accept.split(',')
  if (!acceptTypes.includes('.' + type)) {
    showFailToast('请上传' + props.accept + '格式')
    return false
  }
  if (file.size > maxSize.value) {
    showFailToast('文件大小不能超过' + props.max + 'MB')
    return false
  }
  return true
}

watch(
  () => props.modelValue,
  (val: string) => {
    const arr = val ? val.split(",").filter(item => !!item) : [];
    imgList.value = arr.map(item => {
      return { url: item };
    });
  },
  { immediate: true }
);
</script>

<style scoped lang="less">
.tips {
  font-size: 0.9rem;

  span {
    margin: 0 0.2rem;
    color: #ff4350;
  }
}
</style>
